package org.fly.filter;

import org.fly.bean.User;
import org.fly.contants.WebConstant;
import org.fly.utils.CacheUtil;
import org.fly.utils.UserContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author fly
 */
public class AdminLoginFilter extends LoginFilter{






    /**
     * 通过cookie获取用户信息
     * @param request
     * @return
     */
    protected User getUser(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if(cookies ==null){
            return null;
        }
        Map<String,String> cookieMap = cookie2map(cookies);
        String token = cookieMap.get(WebConstant.cookie_token);
        User user = CacheUtil.getByKey(token);
        if(user != null ){
            Map<String,String> storedCookie = user.getCookieMap();
            boolean allMatch = storedCookie.entrySet().stream().map(e->e.getValue().equals(cookieMap.get(e.getKey()))).
                    reduce(true,(a,b)->a&&b);
            if(!allMatch){
                return null;
            }else {
                return user;
            }
        }
        return null;
    }

    @Override
    public List<String> getExcludeUri() {
        return excludeUri;
    }

    @Override
    public void setExcludeUri(List<String> excludeUri) {
        this.excludeUri = excludeUri;
    }

    @Override
    public String getLoginUri() {
        return WebConstant.adminLoginUrl;
    }

}
